<?php

namespace App\Http\Resources;

use App\Models\Configuration;
use App\Models\GoodsOrder;
use App\Models\GoodsOrderDetail;
use App\Models\ShippingAddress;
use Carbon\Carbon;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Http\Request;

class GoodsOrderResource extends JsonResource
{
    const ORDER_STATUS = [
        GoodsOrder::ORDER_UNPAID => 'Pending',
        GoodsOrder::ORDER_PAID => 'Pending-D',
        GoodsOrder::ORDER_NOT_RECEIVED => 'Unreceived',
        GoodsOrder::ORDER_REFUND => 'Refund',
        GoodsOrder::ORDER_REFUNDED => 'Refunded',
        GoodsOrder::ORDER_CANCEL => 'Trading closed',
        GoodsOrder::ORDER_TIME_OUT_CANCEL => 'Trading closed',
        GoodsOrder::ORDER_END => 'Completed',
        GoodsOrder::ORDER_SELL => 'On Sell',
        GoodsOrder::ORDER_SELL_SUCCESS => 'Successful trade',
        GoodsOrder::ORDER_SELL_FAIL => 'Transaction failure',
    ];
    /**
     * @param Request $request
     * @return array
     */
    public function toArray($request): array
    {
        $data = parent::toArray($request);
        foreach ($data['order_detail'] as &$order_detail){
            $order_detail['img'] = strpos($order_detail['img'],'https') === false ? sprintf('%s%s', aliyun_domain(), $order_detail['img']) : $order_detail['img'];
        }

        //订单状态类型转换
        $data['order_status_string'] = self::ORDER_STATUS[$data['order_status']];

        //支付时间
        if(!empty($data['pay_time'])) {
            $data['pay_time'] = Carbon::parse($data['pay_time'])->rawFormat('M j, Y g:i A');
        }
        //完成时间
        if(!empty($data['complete_time'])) {
            $data['complete_time'] = Carbon::parse($data['complete_time'])->rawFormat('M j, Y g:i A');
        }
        $data['waiting_payment'] = 0;
        if($data['order_status'] == GoodsOrder::ORDER_UNPAID){
            $data['waiting_payment'] = Carbon::parse($data['add_time'])->addMinutes(Configuration::getItem('waiting_payment'))->timestamp;
        }
        if(!empty($data['created_at'])) {
            $data['created_at'] = Carbon::parse($data['created_at'])->rawFormat('M j, Y g:i A');
        }
        if(!empty($data['add_time'])) {
            $data['add_time'] = Carbon::parse($data['add_time'])->rawFormat('M j, Y g:i A');
        }
        //拼接物流信息
        if(!empty($data['goods_logistics'])) {
            foreach ($data['goods_logistics'] as &$log){
                if(!empty($log['messagesystem'])){
                    $msg = trans('validation.logistics')[$log['messagesystem']];
                    if($log['messagesystem'] == "arrival"){
                        $shipping_address = ShippingAddress::getAdd($log['shipping_address_id']);
                        $msg = sprintf($msg,$shipping_address['address']);
                    }
                    $log['message'] = $msg;
                }
            }
        }


        return $data;
    }
}
